<?php
class CV_Datastore_Metadata_Relational_Provider_Mysql implements CV_Datastore_Metadata_Relational_Provider{
	private $_pdo;
	/**
	 * 
	 * @param $pdo CV_PDO
	 * @return unknown_type
	 */
	function __construct( $pdo ){
		$this->_pdo = $pdo;
	}
	function fetch( $databases ){
		$pdo = $this->_pdo;
		
		$databases_metadata = 
			CV_Array::reindex( 
				$pdo->fetchAll( 'SELECT * FROM information_schema.schemata WHERE schema_name IN ('.$pdo->markers($databases).')', $databases )
				, 'SCHEMA_NAME'
			);

		$tables_metadata = CV_Array::reindex( 
			$pdo->fetchAll( 'SELECT * FROM information_schema.tables WHERE table_schema IN ('.$pdo->markers($databases).')', $databases )
			, array( 'TABLE_SCHEMA', 'TABLE_NAME' )
		);
		$columns_metadata = CV_Array::reindex(
			$pdo->fetchAll( 'SELECT * FROM information_schema.columns WHERE table_schema IN ('.$pdo->markers($databases).')', $databases )
			, array( 'TABLE_SCHEMA', 'TABLE_NAME', 'COLUMN_NAME' )
		);
		//print_r($columns_metadata);
		foreach( $columns_metadata as $database_name => $columns_metadata_by_database ){
			$database = new CV_Datastore_Metadata_Relational_Provider_Mysql_Database( $databases_metadata[$database_name] );
			$tables = array();
			foreach( $columns_metadata_by_database as $table_name => $columns_metadata_by_table ){
				$table = new CV_Datastore_Metadata_Relational_Provider_Mysql_Table( $tables_metadata[$database_name][$table_name], $database );
				$columns = array();
				foreach( $columns_metadata_by_table as $column_name => $columns_metadata_by_column ){
					$columns[$column_name] = new CV_Datastore_Metadata_Relational_Provider_Mysql_Column( $columns_metadata_by_column, $table );
				}
				$table->set_columns( $columns );
				$tables[$table_name] = $table;
			}
			$database->set_tables( $tables );
			$this->databases[$database_name] = $database;
		}
	}
	function get_databases(){
		return $this->databases;
	}
	function offsetGet( $database ){
		return $this->databases[ $database ];
	}
	function offsetSet( $name, $value ){}
	function offsetIsset( $name ){}
	function offsetUnset( $name ){}	 
}